package com.zmn.oms.third.deshiman.service.impl;

import com.alibaba.fastjson.JSON;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.http.HttpUtil;
import com.zmn.oms.business.interfaces.notifylog.OrderNotifyLogBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.model.dto.open.v2.PushOrderDTO;
import com.zmn.oms.model.entity.chan.plat.ChannelInterface;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkLogChange;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.deshiman.DeshimanConsts;
import com.zmn.oms.zmn.business.interfaces.chan.ChannelInterfaceBService;
import com.zmn.oms.zmn.business.interfaces.open.OrderChangeNotifyService;
import com.zmn.oms.zmn.business.interfaces.open.v2.V2OrderStatusSyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 类描述：德施曼渠道推送订单变化通知的服务
 *  对接后期德施曼方提出了新需求：啄木鸟向德施曼同步订单状态时，需增加“空跑费”状态同步功能。
 *  为了满足德施曼方的状态同步需求，同时不破坏啄木鸟新系统中的标准对接接口规范，
 *  故将德施曼方的同步订单状态接口做了单独定制，未使用啄木鸟新系统的标准对接接口；
 *
 * @author lhl
 * @date 2020/04/08 15:27
 */
@Service("deshimanNotifyService")
@Slf4j
public class DeshimanNotifyServiceImpl implements OrderChangeNotifyService {

    @Autowired
    private V2OrderStatusSyncService v2OrderStatusSyncService;
    @Autowired
    private OrderNotifyLogBService orderNotifyLogBService;
    @Autowired
    private OrderServiceItemService orderServiceItemService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private ChannelInterfaceBService channelInterfaceBService;

    /**
     * 推送订单状态
     * @param orderWorkLogChange
     */
    @Override
    @SuppressWarnings("all")
    public void notifyChange(OrderWorkLogChange orderWorkLogChange) {
        int logType = orderWorkLogChange.getLogType().intValue();

        ResultDTO resultDTO = null;
        // 修改预约时间
        if (isChangeDutyTime(logType, orderWorkLogChange)) {
            resultDTO = v2OrderStatusSyncService.pushDutyTime(orderWorkLogChange);
        }
        // 派单
        else if (OrderLogConsts.ORDER_LOG_TYPE_DISTRIBUTE == logType) {
            resultDTO = v2OrderStatusSyncService.pushMasterInfo(orderWorkLogChange);
        }
        // 上门
        else if (OrderLogConsts.ORDER_LOG_TYPE_VISIT == logType) {
            resultDTO = v2OrderStatusSyncService.pushMasterVisit(orderWorkLogChange);
        }
        // 取消、失败、弃单
        else if (OrderLogConsts.ORDER_LOG_TYPE_CANCEL == logType || OrderConsts.ORDER_OP_TYPE_FAIL == logType
                || OrderConsts.ORDER_OP_TYPE_DISCARD == logType) {
            resultDTO = v2OrderStatusSyncService.pushOrderCancel(orderWorkLogChange);
        }
        // 服务完成
        else if (OrderLogConsts.ORDER_LOG_TYPE_SERVICE_COMPLETE == logType) {
            resultDTO = v2OrderStatusSyncService.pushServiceComplete(orderWorkLogChange);
        }
        // 完成
        else if (OrderLogConsts.ORDER_LOG_TYPE_COMPLETE == logType) {
            // 完成时，如果是“空跑单”，则同步“空跑”状态，不再同步完成状态
            if (isVisitedOnly(orderWorkLogChange)) {
                resultDTO = pushOrderVisitedOnly(orderWorkLogChange);
            }
            else {
                resultDTO = v2OrderStatusSyncService.pushOrderComplete(orderWorkLogChange);
            }
        }
        // 商家备注
        else if (OrderLogConsts.ORDER_LOG_TYPE_FACTORY_REMARK == logType) {
            resultDTO = v2OrderStatusSyncService.pushFactoryRemark(orderWorkLogChange);
        }

        // 保存同步日志
        if (resultDTO != null) {
            orderNotifyLogBService.saveNotifyLog(resultDTO);
        }
    }

    /**
     * 是否是"空跑”单
     * 判定空跑单的条件：服务项ID为：1118494 或 1118495；
     * @param orderWorkLogChange
     * @return
     */
    private boolean isVisitedOnly(OrderWorkLogChange orderWorkLogChange) {
        List<OrderServiceItem> orderServiceItems = orderServiceItemService.listByOrderId(orderWorkLogChange.getOrderId());

        if (CollectionUtils.isNotEmpty(orderServiceItems)) {
            for (OrderServiceItem item : orderServiceItems) {
                Integer servItemId = item.getServItemId();
                if (servItemId == 6379 || servItemId == 6381) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 同步空跑状态
     * @param orderWorkLogChange
     * @return
     */
    private ResultDTO pushOrderVisitedOnly(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();

        ChannelInterface channelInterface = getChannelInterface(orderWorkLogChange.getChannelId());
        String pushUrl = channelInterface == null ? null : channelInterface.getInterfaceStatusUrl();
        if (StringUtils.isBlank(pushUrl)) {
            return null;
        }

        OrderWork dbOrderWork = orderWorkService.findOrderWorkByKey(orderId, orderWorkLogChange.getWorkId());
        String remark = dbOrderWork.getMasterRemark();
        if (StringUtils.isBlank(remark)) {
            remark = "用户取消服务";
        }

        PushOrderDTO jsonData = new PushOrderDTO();
        jsonData.setOrderId(String.valueOf(orderId));
        jsonData.setThirdOrderId(orderWorkLogChange.getOuterId());
        Date optTime = Optional.ofNullable(orderWorkLogChange.getOpTime()).orElse(new Date());
        jsonData.setOptTime(optTime.getTime()/1000);
        jsonData.setRemark(remark);

        String appSecret = channelInterface.getAppSecret();
        Map<String, String> params = v2OrderStatusSyncService.newRequestParams(channelInterface.getChannelId(),
                appSecret, DeshimanConsts.FUNID_VISITED_ONLY, jsonData, "2");

        log.info("[Deshiman] <sync-order-status> request: orderId=[{}], url=[{}], data=[{}]",
                orderId, pushUrl, JSON.toJSONString(params));
        String response = HttpUtil.post(pushUrl, params);
        log.info("[Deshiman] <sync-order-status> response: orderId=[{}], response=[{}]", orderId, response);

        return v2OrderStatusSyncService.toResultDTO(orderWorkLogChange, DeshimanConsts.NOTIFY_STATUS_VISITED_ONLY, response);
    }

    /**
     * 获取渠道接入数据
     * @param channelId
     * @return
     */
    private ChannelInterface getChannelInterface(Integer channelId) {
        Optional<ChannelInterface> optional = channelInterfaceBService.findByChannelId(channelId);
        if (!optional.isPresent()) {
            return null;
        }

        ChannelInterface channelInterface = optional.get();
        if (channelInterface.getStatus() != null && !Objects.equals(GlobalConsts.YES, channelInterface.getStatus())) {
            return null;
        }

        return channelInterface;
    }

}
